Count the character frequency¶
Count the number of characters (character frequency) in a string.
Sample String :
google.com
Expected Result :
{‘o’: 3, ‘g’: 2, ‘.’: 1, ‘e’: 1, ‘l’: 1, ‘m’: 1, ‘c’: 1}
def char_frequency(S):
D = {}
for chr in S:
if chr in D.keys():
D[chr] += 1
else:
D[chr] = 1
return D
# test
print(char_frequency('google.com'))
Output:
{'o': 3, '.': 1, 'g': 2, 'l': 1, 'e': 1, 'c': 1, 'm': 1}